package br.com.ordersys.web.menu;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import br.com.ordersys.framework.restlayer.IResponseBody;

@XmlRootElement(name = "menu")
public class Menu implements IResponseBody {
	@XmlElement(name = "item")
	@XmlElementWrapper(name = "itens")
	private List<MenuItem> itens;
	
	@XmlTransient
	private Comparator<MenuItem> comp = new Comparator<MenuItem>() {

		@Override
		public int compare(MenuItem o1, MenuItem o2) {
			return o1.getDescription().compareTo(o2.getDescription());
		}
	};

	public Menu(List<MenuItem> itens) {
		this.itens = itens;
	}

	public List<MenuItem> getItens() {
		return itens;
	}

	public void sort() {
		Collections.sort(itens, comp);

		for (MenuItem mi : itens) {
			doSort(mi);
		}
	}

	private void doSort(MenuItem mi) {
		if(mi.getSubMenu() != null){
			Collections.sort(mi.getSubMenu(), comp);
			
			for (MenuItem item : mi.getSubMenu()) {
				doSort(item);
			}
		}
	}
}
